import (
	"fmt"
	"math/big" // Use big.Int for safe large number conversion
	"os"
	"strings"
	"time"

	"github.com/bwmarrin/snowflake" // Import the snowflake library
)

// Base62 characters - sorted for clarity, order matters for encoding/decoding
const base62Chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
const base = 62

// Int64ToBase62 encodes an int64 (treated as uint64) to a Base62 string.
func Int64ToBase62(n int64) string {
	if n == 0 {
		return string(base62Chars[0])
	}

	// Use big.Int for calculations to handle large uint64 values correctly
	num := big.NewInt(n)
	baseBig := big.NewInt(base)
	zero := big.NewInt(0)
	rem := big.NewInt(0) // To store the remainder

	var result strings.Builder

	// Handle potential negative int64 if needed, but Snowflake IDs are typically positive.
	// For simplicity here, we assume positive Snowflake IDs or treat as uint64 via big.Int.
	// If n could be negative in other contexts, add specific handling.

	for num.Cmp(zero) > 0 {
		// num.DivMod(num, baseBig, rem) calculates num = num / baseBig and stores remainder in rem
		num.DivMod(num, baseBig, rem)
		// Append the character corresponding to the remainder
		result.WriteByte(base62Chars[rem.Int64()]) // Use Int64() to get remainder value
	}

	// The result is reversed, so we need to reverse it back
	return reverseString(result.String())
}

// reverseString reverses a string
func reverseString(s string) string {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}